<script setup>
import useAuthStore from '@/store/auth'
import api from '@/api'
import { showNotify } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { ref } from 'vue';

const $authStore = useAuthStore()
const $router = useRouter()
const $route = useRoute()

const id = $route.query.id
function getAfterDuplicateChar(str, char) {
  const regex = new RegExp(char + '(.*)', 'g');
  const match = str.match(regex);
  if (match && match[0]) {
    console.warn('match[0].substring(char.length)',match[0].substring(char.length))
    return match[0].substring(char.length);
  }
  return null;
}
const getUserFeedBackDetails = async() => {
  try {
    const res = await api.get('feedback/userFeedBackDetails?id=' + id)
    console.log('getUserFeedBackDetails',res)
    title.value = res.data.title
    content.value = res.data.content

    var source = res.data.image
    var arr = []
    if(source) {
      var sourceList = source.split(",")
      for(let item of sourceList) {
        arr.push({
          type: item.substring(item.lastIndexOf("\.") + 1, item.length),
          url: item
        })
      }
    }
    fileList.value = arr
    replies.value = res.data.replies || {}
  } catch (error) {
    console.error(error)
  }
}

const loading = ref(false)
const title = ref('')
const content = ref('')
const fileList = ref([])
// const fileList = ref([
//   {
//     type: 'mp4',
//     url: 'https://yunpin-video-record.oss-cn-shanghai.aliyuncs.com/uploads/WeChat_20220813210952.mp4'
//   },
//   {
//     type: 'png',
//     url: 'https://yunpin-video-record.oss-cn-shanghai.aliyuncs.com/zhixue/image/20240928/d322b14b0a61d13f1d05b97955deb2be13c04a8563261591825bb55b340f5926.png'
//   }
// ])
const replies = ref({})
const disabled = ref(false)

const isUploading = ref(false)
const allInfoList = ref([])
const url = ref('')  //弹窗展示的图片/视频路径
const urlType = ref('')  //弹窗展示的类型

const show = ref(false)
const currentViewFile = ref({})
//限制上传的内容为视频或图片
// const beforeRead = async (file) => {
//       if (!file.type.startsWith('image') && !file.type.startsWith('video')) {
//         console.log('请上传图片或视频')
//         return false
//       }
//       return true
//     }
const delItem = async (index) => {
  fileList.value.splice(index, 1)
}

const viewFile = async (item) => {
  currentViewFile.value = item
  show.value = true
}

const afterRead = async (file) => {
  console.log('file',file)
  const formData = new FormData();
  formData.append('file', file.file);
  const res = await api.post('upload', formData)

  var fileType = file.file.type.substr(
    file.file.type.lastIndexOf("/") + 1,
    file.file.type.length
  );
  console.log('fileType',fileType)
  fileList.value = fileList.value.concat([{
    url: res.url,
    type: fileType
  }])
}

const submit = async() => {
  console.log('fileList.value',fileList.value)
  if (!title.value) {
    showNotify({ type: 'danger', message: '请输入标题' })
    return
  }
  if (!content.value) {
    showNotify({ type: 'danger', message: '请输入内容' })
    return
  }
  // if(!fileList.value.length) {
  //   showNotify({ type: 'danger', message: '请上传图片' })
  //   return false
  // }
  loading.value = true
  try {
    const res = await api.post('feedback/subFeedBack', {
      title: title.value,
      content: content.value,
      image: fileList.value.length ? fileList.value.map((e)=> e = e.url).toString() : ''
    })
    console.log('res',res)
    showNotify({ type: 'success', message: res.message })
    setTimeout(()=>{
      $router.back()
    }, 1500)
  } catch (error) {
    console.error(error)
  }
  loading.value = false
}


if(id) {
  getUserFeedBackDetails()
  disabled.value = true
}
</script>

<template>
  <div class="page-profile">
    <van-cell-group>
      <van-field
        type="textarea"
        v-model="title"
        label="标题"
        placeholder="请输入标题"
        rows="1"
        autosize
        required
        :readonly="disabled"
      />

      <van-field
        type="textarea"
        v-model="content"
        label="内容"
        placeholder="请输入内容"
        rows="1"
        autosize
        required
        :readonly="disabled"
      />

      <van-field
        center
        readonly
        :border="false"
        label="图片或视频"
      >
      </van-field>
      <van-cell>
        <!-- <van-uploader
          accept="*"
          v-model="imgList"
          :after-read="afterRead"
          :before-read="beforeRead"
          preview-size='25vw'
          @click-preview="handleclicksc"
          :before-delete="afterDelete"
          :preview-full-image="false"
          :disabled="isUploading?true:false"
          /> -->
        <!--点击图片或视频出现放大图片或播放视频的弹窗-->
        <van-overlay :show="show" @click="show = false">
          <div class="wrapper">
            <div class="pr">
              <div @click="show = false" class="icon_close">
                <van-icon name="cross" color="#ffffff" />
              </div>
              <video class="block" autoplay width="100%" v-if="currentViewFile.type == 'mp4'" :src="currentViewFile.url" controls></video>
              <img class="block" style="width: 100%;" v-else :src="currentViewFile.url">
            </div>
          </div>
        </van-overlay>
        <div>
          <!-- <div v-for="(item,index) in fileList" :key="index">
            <video v-if="item.type=='video'" :src="item.url"></video>
            <img v-else :src="item.url" alt="">
          </div> -->
          <div class="cori_upload_cells">
            <div class="cori_upload_cell" v-for="(item,index) in fileList" :key="index">
              <div v-if="!id" @click="delItem(index)" class="icon_close">
                <van-icon name="cross" color="#ffffff" />
              </div>
              
              <video @click="viewFile(item)" width="100%" v-if="item.type=='mp4'" :src="item.url"></video>
              <img @click="viewFile(item)" v-else :src="item.url" alt="">

              <div v-if="item.type=='mp4'" class="icon_play">
                <van-icon name="play-circle-o" />
              </div>
            </div>
            <van-uploader accept="*" v-if="!id"  :after-read="afterRead" />
          </div>
        </div>
        
      </van-cell>
    </van-cell-group>

    <template v-if="replies.content">
      <div style="width: 100%;height: 20px;"></div>
      <van-cell-group>
        <van-field
          type="textarea"
          v-model="replies.content"
          label="回复"
          placeholder="请输入回复"
          rows="1"
          autosize
          required
          :readonly="disabled"
        />
      </van-cell-group>
    </template>

    <div v-if="!id" class="btn_submit">
      <van-button :loading="loading" @click="submit" type="primary" block>提交</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page-profile {
  width: 100vw;
  height: 100vh;
  background: #f7f8fa;

  .btn_submit {
    margin: 100px 24px 20px;
  }

  .cori_upload_cells {
    display: flex;
    flex-wrap: wrap;
  }

  .cori_upload_cell {
    position: relative;
    width: 80px;
    height: 80px;
    margin: 0 5px 5px 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cori_upload_cell img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .cori_upload_cell video {
    width: 100%;
    height: 100%;
  }

  .icon_close {
    position: absolute;
    // z-index: 1;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.6);
  }

  .icon_play {
    position: absolute;
  }

  .wrapper {
    position: relative;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 99;
  }

  .pr {
    width: 80%;
    position: relative;
  }

  .block {
    display: block;
  }
}
</style>

<style scoped>
/deep/ .van-cell__value {
  text-align: left;
}
</style>
